/** * @description : 查看周边零售户 * @descriptionDetail : 查看周边零售户 * @copyright : 浙江烟草 * @author : mc * @create : 2022-12-05 11:06:33 */
<template>
	<view class="page">
		<!-- #ifdef H5-ONLY -->
		<theme-navbar :isWhite="true" backText="返回" title="查看周边零售户">
			<view class="nav-right-icon">
				<u-icon color="#027aff" name="checkmark" size="38" @click="cutScreen('container')"></u-icon>
			</view>
		</theme-navbar>
		<!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		 <fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
		<view class="content">
			<!-- 地图展示 -->
			<view :style="{width: getContainerWidth(), height: getContainerHeight()}" id="container"></view>
			<view class="cur-loc">
				<u-icon name="eye-off" :color="iconColor" size="50" @click="isShowAllMarkers" />
			</view>
			<view class="cur-list">
				<u-icon name="list" :color="iconColor" size="50" @click="infoShowList" />
			</view>
		</view>
		<u-popup mode="right" length="60%" v-model="infoShow">
			<u-tabs :list="tabList" :is-scroll="false" :current="currentTab" @change="changeTab"></u-tabs>
			<u-line color="info" />
			<view v-for="(item,index) in newSchoolList" :key="index">
				<view class="pop-list" v-show="currentTab==0">
					<view>{{ item.name }}</view>
					<view>{{ item.distance }}米</view>
				</view>
			</view>
			<view v-for="(item,index) in newArchiveList" :key="index">
				<u-row gutter="16" class="pop-list" justify="space-between" v-show="currentTab==1">
					<u-col span="9">
						<view>{{ item.companyName }}</view>
					</u-col>
					<u-col span="3" text-align="right">
						<view>{{ item.distance }}米</view>
					</u-col>
				</u-row>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		AMapMixin,
	} from '@/common/AMapMixin.js';
	import certificateService from '@/service/certificate/certificate.service.js';
	import html2canvas from 'html2canvas';
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			fabButton
		},
		mixins: [AMapMixin, ],
		data() {
			return {
				markers: [],
				currPosition: undefined,
				archiveList: [],
				schoolList: [], // 周围学校列表
				northeastLatitude: '',
				northeastLongitude: '',
				southwestLatitude: '',
				southwestLongitude: '',
				iconColor: '',
				isHideIcon: false, // 是否隐藏大于200米的零售户
				routeLine: undefined, // 路线图层
				startMarker: undefined, // 路线起始坐标
				endMarker: undefined, // 路线结束坐标
				isNearSchool: false, // 是否中小学周围
				isNearKindergarten: false, // 是否幼儿园周围
				schoolDis: 200, // 50米
				nearSchoolDesc: '',
				retailerDis: 200, // 50米
				nearGartenDesc: '',
				defaultLongitude: undefined,
				defaultLatitude: undefined,
				infoShow: false,
				tabList: [{
					name: '学校信息',
				}, {
					name: '零售户信息',
				}, ], // tab栏目
				currentTab: 0,
				schoolShowInfo: [],
				newArchiveList: [],
				newSchoolList: [],
				fContent: [{
					iconPath: require('@/static/confirm.png'),
					selectedIconPath: require('@/static/confirm.png'),
					text: '确定',
					active: false,
				}],
			};
		},
		onLoad() {
			let param = this.getRouteParam();
			if (param) {
				this.defaultLongitude = param.longitude;
				this.defaultLatitude = param.latitude;
			}
		},
		mounted() {
			this.init();
		},
		methods: {
			setRightBtns() {
				// 设置右侧标题
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight('确定', () => {
					this.cutScreen('container');
					this.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.cutScreen('container');
				}
			},
			init() {
				this.$modal.showLoading('地图加载中...');
			},
			initAmap() {
				let self = this;
				if (this.defaultLongitude && this.defaultLatitude) {
					self.curPos = [this.defaultLongitude, this.defaultLatitude, ];
					self.setMapInstance([this.defaultLongitude, this.defaultLatitude, ]);
				} else {
					this.getCurrentLocation().then(
						(res) => {
							self.curPos = [res.lng, res.lat, ];
							self.setMapInstance([res.lng, res.lat, ]);
						},
						(err) => {
							self.justInitMap();
						}
					);
				}
			},
			setMapInstance(cords) {
				if (!this.hasInited) return;
				let self = this;
				self.curCords = new AMap.LngLat(cords[0], cords[1]);
				self.amap = new AMap.Map('container', {
					center: self.curCords,
					showControlButton: true,
					zoom: 18,
					WebGLParams: {
						preserveDrawingBuffer: true,
					},
					resizeEnable: true, // 监控地图容器尺寸变化
				});
				self.setCurrentPointMarker();
				this.$modal.hideLoading();
				self.loadPlugin(['AMap.ToolBar', 'AMap.Scale', 'AMap.OverView', 'AMap.MapType', ], function() {
					// 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
					self.amap.addControl(new AMap.ToolBar());
					// 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
					self.amap.addControl(new AMap.Scale());
					// 在图面添加定位控件，用来获取和展示用户主机所在的经纬度位置
					let geolocation = new AMap.Geolocation({
						enableHighAccuracy: true, // 是否使用高精度定位，默认:true
						timeout: 10000, // 超过10秒后停止定位，默认：5s
						// buttonPosition:'RB',    //定位按钮的停靠位置
						buttonOffset: new AMap.Pixel(5, 10), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
						// zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
						content: '<img src="https://a.amap.com/jsapi_demos/static/resource/img/user.png" style="width:36px;height:36px"/>',
					});
					self.amap.addControl(geolocation);
				});
				self.amap.on('click', (rs) => {
					if (self.routeLine) {
						self.amap.remove(self.routeLine);
						self.amap.remove(self.startMarker);
						self.amap.remove(self.endMarker);
						self.routeLine = undefined;
						self.startMarker = undefined;
						self.endMarker = undefined;
						self.amap.setFitView();
					}
				});
				self.getNearRetailer();
			},
			// 获取列表数据
			getNearRetailer() {
				let bounds = this.amap.getBounds();
				let params = {
					// lng1 : bounds.southwest.lng,
					// lat1 :bounds.southwest.lat,
					// lng2: bounds.northeast.lng,
					// lat2: bounds.northeast.lat,
					currentLongitude: this.curPos[0],
					currentLatitude: this.curPos[1],
					distance: this.retailerDis,
				};
				let self = this;
				self.$modal.showLoading('正在查询周边零售户...');
				// certificateService.getRetailerMapList(params).then((res) => {
				certificateService
					.getLicenseInfoByLonLat(params)
					.then((res) => {
						self.$modal.hideLoading();
						if (res.success) {
							self.markers = [];
							self.archiveList = res.data;
							if (res.data.length != 0) {
								let arr = res.data.map(({
									latitude,
									longitude,
								}) => {
									return `${longitude},${latitude}`;
								});
								let des = `${self.curPos[0]},${self.curPos[1]}`;
								let SERVER_KEY = process.uniEnv.AMAP.SERVER_KEY;

								self
									.getCurDistance({
										destination: des,
										key: SERVER_KEY, // 很重要，不能删，占位置
										origins: arr.join('|'),
										output: 'JSON',
										type: 3,
									})
									.then((rs) => {
										self.archiveList = res.data.map((item, index) => {
											return {
												...item,
												...rs[index],
											};
										});
										self.archiveList.forEach((retailer, index) => {
											self.addMarker(retailer, res.data);
										});
										self.newArchiveList = self.archiveList;
									});
							} else {
								self.$u.toast('该区域内没查询到零售户信息！');
							}
						} else {
							self.$modal.hideLoading();
							self.$u.toast(res.msg);
						}
					})
					.catch((error) => {
						self.$u.toast(error);
					});
				this.querySchool();
			},
			// 在地图上添加点
			addMarker(retailer, retailerData) {
				let self = this;
				let markPoint = {
					title: `${retailer.companyName},${retailer.distance}米`,
					icon: new AMap.Icon({
						size: new AMap.Size(24, 24), // 图标尺寸
						image: Number(retailer.distance) <= this.retailerDis ? 'static/certificate/store_red.png' : 'static/certificate/store_blue.png', // 大图地址
						imageSize: new AMap.Size(24, 24), //,
					}),
					label: null,
					position: [retailer.longitude, retailer.latitude, ],
					extData: {
						id: retailer.retailerUuid,
						distance: retailer.distance,
					},
				};
				if (Number(retailer.distance) <= this.retailerDis) {
					markPoint.label = {
						content: `${retailer.companyName},${retailer.distance}米`,
						offset: new AMap.Pixel(22, 1),
					};
				}
				let point = new AMap.Marker(markPoint);
				point.setMap(self.amap); // 在地图上添加点
				point.on('click', function() {
					self.showRoute('retail', retailer);
				});
				self.markers.push(point);
			},
			// 在地图上添加中小学标记点
			addSchoolMarker(school, schoolsData) {
				let self = this;
				let pos = school.location.split(',');
				let markPoint = {
					title: `${school.name},${school.distance}米`,
					icon: new AMap.Icon({
						size: new AMap.Size(24, 24), // 图标尺寸
						image: Number(school.distance) > this.schoolDis ? 'static/certificate/school_blue.jpg' : 'static/certificate/school_red.jpg', // 大图地址
						imageSize: new AMap.Size(24, 24), //,
					}),
					label: null,
					position: [Number(pos[0]), Number(pos[1]), ],
					extData: {
						id: school.id,
						distance: school.distance,
					},
				};
				if (Number(school.distance) < this.schoolDis) {
					if (school.type.indexOf('幼儿园') != -1) {
						this.isNearKindergarten = true;
						this.nearGartenDesc = school.name + '相距步行距离' + school.distance + '米';
					} else {
						this.isNearSchool = true;
						this.nearSchoolDesc = school.name + '相距步行距离' + school.distance + '米';
					}
					markPoint.label = {
						content: `${school.name},${school.distance}米`,
						offset: new AMap.Pixel(22, 1),
					};
				}
				let point = new AMap.Marker(markPoint);
				point.setMap(self.amap); // 在地图上添加点
				point.on('click', function() {
					self.showRoute('school', school);
				});
				self.markers.push(point);
			},
			infoShowList() {
				this.infoShow = true;
			},
			changeTab(index) {
				this.currentTab = index;
			},
			// 绘制路线
			showRoute(type, retailer) {
				let self = this;
				let des = type == 'school' ? retailer.location : `${retailer.longitude},${retailer.latitude}`;
				self
					.getRoutsData({
						destination: des,
						key: '', // 很重要，不能删，占位置
						origin: `${self.curPos[0]},${self.curPos[1]}`,
						output: 'JSON',
					})
					.then((route) => {
						self.drawRoute(route, des, type, retailer);
					});
			},
			drawRoute(route, des, type, retailer) {
				let self = this;
				let labelContent = type == 'school' ? `${retailer.name},${retailer.distance}米` : `${retailer.companyName},${retailer.distance}米`;
				if (self.routeLine) {
					self.amap.remove(self.routeLine);
					self.amap.remove(self.startMarker);
					self.amap.remove(self.endMarker);
					self.routeLine = undefined;
					self.startMarker = undefined;
					self.endMarker = undefined;
				}
				let pos = des.split(',');
				let path = self.parseRouteToPath(route);
				self.startMarker = new AMap.Marker({
					position: self.curCords,
					icon: 'static/map/start.png',
					map: self.amap,
				});

				self.endMarker = new AMap.Marker({
					position: [pos[0], pos[1], ],
					title: labelContent,
					label: {
						content: labelContent,
						offset: new AMap.Pixel(22, 1),
					},
					icon: 'static/map/end.png',
					map: self.amap,
				});
				let distance = type == 'school' ? this.schoolDis : this.retailerDis;
				self.routeLine = new AMap.Polyline({
					path: path,
					isOutline: true,
					outlineColor: '#ffeeee',
					borderWeight: 2,
					strokeWeight: 5,
					strokeColor: Number(route.distance) >= distance ? '#0091ff' : '#FF6A71',
					strokeOpacity: 0.9,
					lineJoin: 'round',
				});
				self.endMarker.setMap(self.amap);
				self.routeLine.setMap(self.amap);
				// self.amap.add(routeLine);
				// 调整视野达到最佳显示区域
				self.amap.setFitView([self.startMarker, self.endMarker, self.routeLine, ]);
			},
			// 解析WalkRoute对象，构造成AMap.Polyline的path参数需要的格式
			parseRouteToPath(route) {
				let path = [];
				for (let i = 0, l = route.steps.length; i < l; i++) {
					let step = route.steps[i];
					let polyline = step.polyline.split(';');
					for (let j = 0, n = polyline.length; j < n; j++) {
						let routeItem = polyline[j].split(',');
						routeItem = [Number(routeItem[0]), Number(routeItem[1]), ];
						path.push(routeItem);
					}
				}
				return path;
			},
			// 查询周边中小学幼儿园信息
			querySchool() {
				let self = this;
				self
					.getAroundSchool({
						key: '', // 很重要，不能删，占位置
						location: `${self.curPos[0]},${self.curPos[1]}`,
						output: 'JSON',
						radius: this.schoolDis,
						types: '初中|小学|幼儿园',
					})
					.then((res) => {
						self.schoolList = res;
						if (res.length > 0) {
							let arr = res.map(({
								location,
							}) => {
								return location;
							});
							let des = `${self.curPos[0]},${self.curPos[1]}`;
							let SERVER_KEY = process.uniEnv.AMAP.SERVER_KEY;
							self
								.getCurDistance({
									destination: des,
									key: SERVER_KEY, // 很重要，不能删，占位置
									origins: arr.join('|'),
									output: 'JSON',
									type: 3,
								})
								.then((rs) => {
									this.schoolShowInfo = res;
									self.schoolList = res.map((item, index) => {
										return {
											...item,
											...rs[index],
										};
									});
									console.log(self.schoolList);
									self.schoolList.forEach((school, index) => {
										self.addSchoolMarker(school, res);
									});
									this.newSchoolList = this.schoolList;
								});
						}
					});
			},
			// 截屏
			cutScreen(id) {
				let element = document.getElementById(id);
				html2canvas(element, {
					backgroundColor: 'transparent',
					logging: false,
				}).then((canvas) => {
					const context = canvas.getContext('2d');
					// 关闭抗锯齿形
					context.mozImageSmoothingEnabled = false;
					context.webkitImageSmoothingEnabled = false;
					context.msImageSmoothingEnabled = false;
					context.imageSmoothingEnabled = false;
					// canvas转化为图片
					let img = this.canvas2Image(canvas, canvas.width, canvas.height, id, '图片');
					this.backPrev({
						paramKey: 'mapImg',
						param: {
							imgSrc: img.src,
							isNearSchool: this.isNearSchool,
							nearSchoolDesc: this.nearSchoolDesc,
							isNearKindergarten: this.isNearKindergarten,
							nearGartenDesc: this.nearGartenDesc,
						},
					});
				});
			},
			// canvas 转化为图片
			canvas2Image(canvas, width, height, id, val) {
				const retCanvas = document.createElement('canvas');
				const retCtx = retCanvas.getContext('2d');
				retCanvas.width = width;
				retCanvas.height = height;
				retCtx.drawImage(canvas, 0, 0, width, height, 0, 0, width, height);
				const img = document.createElement('img');
				img.src = retCanvas.toDataURL('image/png'); // 可以根据需要更改格式
				return img;
			},
			// 是否显示所以零售户信息
			isShowAllMarkers() {
				this.isHideIcon = !this.isHideIcon;
				let hideMarkers = [];
				let showMarkers = [];
				if (this.markers.length > 0) {
					hideMarkers = this.markers.filter((item) => {
						let distance = item.getExtData().distance;
						return Number(distance) > this.retailerDis;
					});
					showMarkers = this.markers.filter((item) => {
						let distance = item.getExtData().distance;
						return Number(distance) <= this.retailerDis;
					});
				}
				if (this.isHideIcon) {
					this.iconColor = '#2979ff';
					hideMarkers.forEach((item) => {
						this.amap.remove(item);
					});
				} else {
					this.iconColor = '';
					hideMarkers.forEach((item) => {
						this.amap.add(item);
					});
				}
			},
			getContainerHeight() {
				return this.$u.sys().windowHeight - this.$u.sys().statusBarHeight + 'px';
			},
			getContainerWidth() {
				return this.$u.sys().windowWidth + 'px';
			},
			justInitMap() {
				this.$modal.alert('请在设备的设置中开启APP的定位权限后重新获取当前位置');
				this.amap = new AMap.Map('container', {
					showControlButton: true,
					zoom: 18,
					WebGLParams: {
						preserveDrawingBuffer: true,
					},
					resizeEnable: true, // 监控地图容器尺寸变化
				});
				this.$modal.hideLoading();
			},
		},
	};
</script>

<style scoped lang="scss">
	@import 'style/certificate/common.scss';

	.search-right-icon {
		display: flex;
		position: absolute;
		right: 8%;
	}

	uni-page-body {
		min-height: 100%;
		width: 100%;
		background-color: #f1f0f6;
	}

	#container {
		width: 100%;
		height: calc(100% - 88px);
	}

	// 搜索框内容
	.u-serach-info {
		background-color: #f4f4f5;
		position: fixed;
		/* #ifdef H5-DINGDING  */
		top: 0px;
		/* #endif */
		/* #ifndef H5-DINGDING  */
		top: calc(var(--status-bar-height) + 44px);
		/* #endif */
		z-index: 1;
		width: 100%;
		padding-right: 11px;

		.u-search-title {
			background: #fff;
			padding: 10px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 44px;
		}

		.u-search-btn {
			height: 44px;
			line-height: 44px;
			// padding: 0 10px;
			display: flex;
			align-items: center;

			.u-confirm-btn {
				height: 32px;
				margin-left: 10px;
			}
		}
	}

	.u-l-item {
		margin-top: 88px;
	}

	.cur-loc {
		position: absolute;
		bottom: 60px;
		left: 15px;
		padding: 5px;
		background: #fff;
		width: 35px;
		height: 35px;
		box-shadow: 0px 0px 0px 1px #ddd;
	}

	.cur-list {
		position: absolute;
		bottom: 109px;
		left: 15px;
		padding: 5px;
		background: #fff;
		width: 35px;
		height: 35px;
		box-shadow: 0px 0px 0px 1px #ddd;
	}

	.pop-list {
		display: flex;
		justify-content: space-between;
		padding: 13px 8px 13px 5px;
		margin: 10px 5px 10px 5px;
		background-color: #ffffff;
		font-size: 13px;
	}

	.archive-list {
		// margin-left: 2px;
	}

	/deep/.u-drawer-right {
		background-color: #eff3f9;
	}
</style>
